<template>
  <div class="bgc-default pad-20">
    <div class="bg-color-white pad-20">
      <div>
        <el-button type="primary" @click="handleCreate">新增海报</el-button>
      </div>
      <!--顶部搜索 -->
      <div class="top-operate-default none-bg mar-t-20 mar-b-20">
        <div class="search-item">
          <label class="pad-r-10">海报名称：</label>
          <el-input @keyup.enter.native="handleSearch" v-model="listQuery.posterTitle" placeholder="请输入关键字" style="width: 260px"></el-input>
          <label class="pad-l-20 pad-r-10">创建时间：</label>
          <el-date-picker
              v-model="starEndTime"
              type="datetimerange"
              align="right"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd HH:mm:ss"
              :default-time="['00:00:00', '23:59:59']">
          </el-date-picker>
          <el-button-group class="mar-l-20">
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="doResetSearch">重置</el-button>
          </el-button-group>
        </div>
      </div>
      <!-- 内容列表 -->
      <div class="table-container">
        <el-table :data="listData" @selection-change="handleSelectionChange" v-loading="listLoading"
                  element-loading-text="加载中"
                  style="width: 100%" border>
          <el-table-column width="55px" type="selection" align="center"></el-table-column>
          <el-table-column width="55px" label="序号" fixed="left" prop="sortNo"></el-table-column>
          <el-table-column label="海报信息" prop="imageUrl">
            <template slot-scope="scope">
              <label><img :src="scope.row.imageUrl" class="user-avatar" height="50"></label>
              <span class="font-14 pad-l-10 v-align-h height-65">{{ scope.row.posterTitle }}</span>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" prop="createTime"></el-table-column>
          <el-table-column width="120px" label="操作" fixed="right">
            <template slot-scope="scope">
              <el-button type="text" size="mini" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="text" size="mini" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 列表分页 -->
      <div class="pagination">
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                      :current-page="listQuery.currentPage"
                      :page-sizes="[10, 20, 50, 100]" :page-size="listQuery.size"
                      layout="total, sizes, prev, pager, next, jumper"
                      :total="total">
        </el-pagination>
      </div>
      <!-- 添加/编辑 -->
      <div>
        <el-dialog width="700px" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
          <el-form ref="dialogForm" :model="poster" label-position="right" label-width="100px" style='width: 500px; margin-left:50px;'>
            <el-form-item label="图片" prop="imageUrl">
              <el-upload class="upload-demo" drag :show-file-list="false"
                action="/api/common/uploadFiles" accept="image/jpeg,image/gif,image/png,image/bmp" :before-upload="beforeUpload" name="files" :data="token" :on-success="handleUploadSuccess">
                <img v-if="poster.imageUrl" :src="poster.imageUrl" height="200px">
                <div v-else>
                  <i class="el-icon-upload"></i>
                  <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                  <div class="el-upload__tip" slot="tip">只能上传jpg/png文件且不超过2M，建议尺寸621x800</div>
                </div>
              </el-upload>
            </el-form-item>
            <el-form-item label="海报名称" prop="posterTitle">
              <el-input v-model="poster.posterTitle" placeholder="最多输入20个字" maxlength="20"></el-input>
            </el-form-item>
            <el-form-item label="海报序号" prop="sortNo">
              <el-input v-model="poster.sortNo"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="saveData">确定</el-button>
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>


<style scoped>
  .editor-container {
    position: relative;
    height: 100%;
  }
</style>

<script>
  import { getNameByPath } from '@/utils/get-name-by-path' // 不要删除，根据URL获取文件名
  import { getToken } from '@/utils/auth'
  import { getPosterList, savePoster, deletePoster } from '@/api/sell/poster'
  import { getStrByLength } from '@/utils'

  export default {
    name: getNameByPath(),
    data() {
      return {
        listData: [],
        total: null,
        listLoading: true,
        poster: {
          enterpriseId: this.getEnterpriseId(),
          posterId: '',
          imageUrl: '',
          sortNo: '',
          posterTitle: ''
        },
        multipleSelection: [],
        listQuery: {
          enterpriseId: this.getEnterpriseId(),
          currentPage: 1,
          size: 10,
          posterTitle: '',
          startTime: '',
          endTime: ''
        },
        starEndTime: [],
        textMap: {
          update: '编辑',
          create: '添加'
        },
        dialogFormVisible: false,
        dialogStatus: '',
        token: {}
      }
    },
    // 过滤器
    filters: {
    },
    // 初始化页面
    created() {
      this.initList()
      this.token = { accessToken: getToken() }
    },
    methods: {
      initList() {
        this.listLoading = true
        getPosterList(this.listQuery).then(response => {
          this.listData = response.data.records
          this.total = response.data.total
          this.listLoading = false
        })
      },
      handleSearch() {
        this.listQuery.currentPage = 1
        if (this.starEndTime) {
          this.listQuery.startTime = this.starEndTime[0]
          this.listQuery.endTime = this.starEndTime[1]
        }
        this.initList()
      },
      resetSearch() {
        this.listQuery = {
          enterpriseId: this.getEnterpriseId(),
          currentPage: 1,
          size: 10,
          posterTitle: '',
          startTime: '',
          endTime: ''
        }
        this.initList()
      },
      handleSizeChange(val) {
        this.listQuery.size = val
        this.initList()
      },
      handleCurrentChange(val) {
        this.listQuery.currentPage = val
        this.initList()
      },
      handleSelectionChange(val) {
        this.listQuery = val
      },
      // 创建时，清除值
      resetForm() {
        this.poster = {
          enterpriseId: this.getEnterpriseId(),
          posterId: '',
          imageUrl: '',
          sortNo: '',
          posterTitle: ''
        }
      },
      // 添加
      handleCreate() {
        this.resetForm()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dialogForm'].clearValidate()
        })
      },
      // 编辑
      handleEdit(row) {
        this.resetForm()
        this.poster = Object.assign(this.poster, row)
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
      },
      // 保存信息
      saveData() {
        this.$refs['dialogForm'].validate((valid) => {
          if (valid) {
            savePoster(this.poster).then(response => {
              if (response.isError) return
              this.initList()
              this.dialogFormVisible = false
              this.$message({
                type: 'success',
                message: '保存成功!'
              })
            })
          }
        })
      },
      // 删除
      handleDelete(row) {
        this.$confirm('此操作将删除该记录，是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deletePoster(row.posterId).then(response => {
            if (response.isError) return
            this.initList()
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          })
        }).catch(() => {})
      },
      beforeUpload(file) {
        const isJPG = file.type === 'image/jpeg'
        const isGIF = file.type === 'image/gif'
        const isPNG = file.type === 'image/png'
        const isBMP = file.type === 'image/bmp'

        if (!isJPG && !isGIF && !isPNG && !isBMP) {
          this.$message.error('上传图片必须是JPG/GIF/PNG/BMP 格式!')
        }
        return (isJPG || isBMP || isGIF || isPNG)
      },
      handleUploadSuccess(res, file) {
        if (res.code === 101) {
          this.poster.imageUrl = res.data[0]
        }
      },
      getStrByLength(str, n) {
        return getStrByLength(str, n)
      }
    },
    mounted() {

    }
  }
</script>
